package com.aduerr.v1shouyin.mvp.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.*;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.PreAuthoCompleteEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.util.LogUtils;
import com.aduerr.v1shouyin.util.NumUtil;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.aduerr.v1shouyin.view.SecurityCodeView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import java.util.HashMap;


/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2019/4/15 18:04
 * @change
 * @chang time
 * @class describe
 */

public class PreAuthoRefundActivity extends AppCompatActivity {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_goods_money)
    TextView tvGoodsMoney;
    @BindView(R.id.tv_deposit)
    TextView tvDeposit;
    @BindView(R.id.tv_refunded)
    TextView tvRefunded;
    @BindView(R.id.ll_refunded_money)
    LinearLayout llRefundedMoney;
    @BindView(R.id.tv_refund_des)
    TextView tvRefundDes;
    @BindView(R.id.tv_refund)
    TextView tvRefund;
    @BindView(R.id.tv_beizhu_calculator)
    TextView tvBeizhuCalculator;
    @BindView(R.id.ll_notify)
    LinearLayout llNotify;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.bt_confirm)
    Button btConfirm;
    @BindView(R.id.ll_deposit)
    LinearLayout llDeposit;
    Dialog dialog;
    SecurityCodeView securityCodeView;
    private double goodsMoney, deposit, refundMoney;
    private String orderId;
    private int orderState;
    private ProgressDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pre_autho_refund);
        ButterKnife.bind(this);
        goodsMoney = getIntent().getDoubleExtra("goods_money", 0);
        deposit = getIntent().getDoubleExtra("deposit", 0);
        orderId = getIntent().getStringExtra("order_id");
        orderState = getIntent().getIntExtra("order_state", -1);
        if(deposit == 0) {
            llDeposit.setVisibility(View.GONE);
        } else {
            llDeposit.setVisibility(View.VISIBLE);
        }

        if(orderState == 2) {
            llRefundedMoney.setVisibility(View.VISIBLE);
            refundMoney = getIntent().getDoubleExtra("refund_money", 0);
            tvRefunded.setText("￥" + NumUtil.formatFloat(refundMoney));
            tvRefundDes.setText("再退还顾客");
            tvRefund.setText("￥" + NumUtil.formatFloat(goodsMoney + deposit - refundMoney));
            tvTitle.setText("完成撤销");
        } else {
            llRefundedMoney.setVisibility(View.GONE);
            tvRefundDes.setText("全额退还顾客");
            tvRefund.setText("￥" + NumUtil.formatFloat(goodsMoney + deposit));
            tvTitle.setText("撤销");
        }

        tvGoodsMoney.setText("￥" + NumUtil.formatFloat(goodsMoney + deposit));
        tvDeposit.setText("￥" + deposit);
    }

    @OnClick({R.id.img_back, R.id.bt_confirm})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.bt_confirm:
                toDialogActivity();
                break;
        }
    }

    private void preAuthoCancel(String password) {

        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("OrderID", orderId);
        addParams.put("Remark", etRemark.getText().toString());
        addParams.put("RefundPassword", password);

        APIRetrofit.getAPIService().preAuthoCancel(RXRequest.getXingPosParams(addParams
                , this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PreAuthoCompleteEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if(loadingDialog == null) {
                            loadingDialog =
                                    new ProgressDialog(PreAuthoRefundActivity.this,
                                            ProgressDialog.STYLE_SPINNER);
                            loadingDialog.setTitle("正在撤销中");
                            loadingDialog.setCanceledOnTouchOutside(false);
                        }
                        loadingDialog.show();
                    }

                    @Override
                    public void onNext(@NonNull PreAuthoCompleteEntity entity) {
                        //                        if (Tools.isAvailable
                        //                        (acquirePayEntity)) return;
                        if(entity.getSuccess() == 1) {
                            Intent intent = new Intent(PreAuthoRefundActivity.this,
                                    PreAuthoOrderActivity.class);
                            intent.putExtra("orderid", orderId);
                            intent.putExtra("tag", "result");
                            startActivity(intent);
                            finish();
                        } else {
                            ToastUtils.showToast(PreAuthoRefundActivity.this,
                                    entity.getErrMsg());
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(loadingDialog != null && loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        ToastUtils.showToast(PreAuthoRefundActivity.this, "网络异常");
                    }

                    @Override
                    public void onComplete() {
                        if(loadingDialog != null && loadingDialog.isShowing())
                            loadingDialog.dismiss();
                    }
                });

    }

    private void preAuthoCompleteCancel(String password) {

        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("OrderID", orderId);
        addParams.put("Remark", etRemark.getText().toString());
        addParams.put("RefundPassword", password);

        APIRetrofit.getAPIService().preAuthoCompleteCancel(RXRequest.getXingPosParams(addParams
                , this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PreAuthoCompleteEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if(loadingDialog == null) {
                            loadingDialog =
                                    new ProgressDialog(PreAuthoRefundActivity.this,
                                            ProgressDialog.STYLE_SPINNER);
                            loadingDialog.setTitle("正在撤销中");
                            loadingDialog.setCanceledOnTouchOutside(false);
                        }
                        loadingDialog.show();
                    }

                    @Override
                    public void onNext(@NonNull PreAuthoCompleteEntity entity) {
                        if(entity.getSuccess() == 1) {
                            Intent intent = new Intent(PreAuthoRefundActivity.this,
                                    PreAuthoOrderActivity.class);
                            intent.putExtra("orderid", orderId);
                            intent.putExtra("tag", "result");
                            startActivity(intent);
                            finish();
                        } else {
//                        ToastUtils.showToast(PreAuthoRefundActivity.this, entity
//                        .getErrMsg());
                            Intent intent2 = new Intent(PreAuthoRefundActivity.this,
                                    PreAuthoFailActivity.class);
                            intent2.putExtra("error_msg", entity.getErrMsg());
                            startActivity(intent2);
                            finish();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(loadingDialog != null && loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        ToastUtils.showToast(PreAuthoRefundActivity.this, "网络异常");
                    }

                    @Override
                    public void onComplete() {
                        if(loadingDialog != null && loadingDialog.isShowing())
                            loadingDialog.dismiss();
                    }
                });
    }

    private void toDialogActivity() {
        View view =
                LayoutInflater.from(PreAuthoRefundActivity.this).inflate(R.layout.dialog_tuikuan, null);
        // 对话框
        dialog = new Dialog(PreAuthoRefundActivity.this);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.show();
        // 设置宽度为屏幕的宽度
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); // 设置宽度
        dialog.getWindow().setAttributes(lp);
        dialog.getWindow().setContentView(view);
        //==================================弹出键盘================================================================
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        //===========================================================================================================
//        InputTools.KeyBoard(et_hexiao, "open");
//        InputTools.HideKeyboard(et_hexiao);
        //findview
        //找到自定义的控件用来显示密码
        securityCodeView = (SecurityCodeView) view.findViewById(R.id.scv_edittext);
        securityCodeView.setInputCompleteListener(new SecurityCodeView.InputCompleteListener() {
            @Override
            public void inputComplete() {
                dialog.hide();
                LogUtils.e("getEditContent", securityCodeView.getEditContent());
                if(orderState == 2) {
                    preAuthoCompleteCancel(securityCodeView.getEditContent());
                } else {
                    preAuthoCancel(securityCodeView.getEditContent());
                }
            }

            @Override
            public void deleteContent(boolean isDelete) {
                //DO NO THING
            }
        });

    }

}
